package org.softmed.action.manager;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.softmed.action.Action;
import org.softmed.action.builder.ActionCreator;
import org.softmed.filehandling.FileUtil;

import com.google.inject.Inject;

public class DefaultActionManager implements ActionManager {
	@Inject
	ActionCreator actionCreator;

	Map<String, ActionCache> actionCache = new HashMap<String, ActionCache>();
	FileUtil util = new FileUtil();

	public Action getAction(String xmlDescription, Object... objects)
			throws Throwable {
		Action clone = null;
		ActionCache cache = actionCache.get(xmlDescription);

		File file = util.getFile(xmlDescription);

		if (cache == null) {
			String xml = util.readFromFile(file);
			Action action = actionCreator.getActionFromXML(xml);
			cache = new ActionCache();
			cache.setTimestamp(file.lastModified());
			cache.getNode().setOriginal(action);
			actionCache.put(xmlDescription, cache);
			clone = cache.getNode().getActionFromPool();
		} else {
			if (file.lastModified() == cache.getTimestamp()) {
				clone = cache.getNode().getActionFromPool();
			} else {

				String xml = util.readFromFile(file);
				Action action = actionCreator.getActionFromXML(xml);
				cache.setTimestamp(file.lastModified());
				cache.getNode().setOriginal(action);
				cache.getNode().rebuild();
				clone = cache.getNode().getActionFromPool();
			}
		}

		// clone.setWorkArea(new WorkArea());

		return clone;

	}
}
